﻿using Newtonsoft.Json;
using OfficeOpenXml;
using System.IO;

public static class ExcelToJsonConverter
{
    public static string Convert(string excelFilePath)
    {
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // 设置许可证上下文

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFilePath)))
        {
            string sheetName = "Sheet1"; // 指定要操作的工作表名称
            ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetName];
            if (worksheet == null)
            {
                throw new ArgumentException($"工作表 '{sheetName}' 不存在");
            }
            int rowCount = worksheet.Dimension.Rows;
            int colCount = worksheet.Dimension.Columns;
            for (int row = 2; row <= rowCount; row++)
            {
                Dictionary<string, object> values = new Dictionary<string, object>();
                for (int col = 1; col <= colCount; col++)
                {
                    string columnName = worksheet.Cells[1, col].Value.ToString();
                    object value = worksheet.Cells[row, col].Value;
                    values.Add(columnName, value);
                }
                rows.Add(values);
            }
        }
        return JsonConvert.SerializeObject(rows);
    }
}